package org.boulderfoodrescue.webapp.client.managers;

import org.boulderfoodrescue.webapp.client.events.DataState;
import org.boulderfoodrescue.webapp.client.events.LoginInfoUpdatedEvent;
import org.boulderfoodrescue.webapp.client.events.LoginInfoUpdatedHandler;
import org.boulderfoodrescue.webapp.client.rpc.LoginServiceAsync;
import org.boulderfoodrescue.webapp.shared.LoginInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class LoginInfoManager {
	private static LoginInfo loginInfo;
	private final LoginServiceAsync loginRPC;
	private final EventBus eventBus;
	public LoginInfoManager(LoginServiceAsync loginRPC, EventBus eventBus)
	{
		this.loginRPC = loginRPC;
		this.eventBus = eventBus;
		bind();
	}

	private void bind()
	{
		eventBus.addHandler(LoginInfoUpdatedEvent.getType(),
				new LoginInfoUpdatedHandler(){
			@Override
			public void onLoginInfoLoading() {
				LoadLoginInfo();
			}
			@Override
			public void onLoginInfoLoadFailed() {
			}
			@Override
			public void onLoginInfoLoadSuccess(LoginInfo loginInfo) {
			}
		});
	}

	private void LoadLoginInfo()
	{
		loginRPC.login(GWT.getHostPageBaseURL(), new AsyncCallback<LoginInfo>() {
			public void onFailure(Throwable error) {
				eventBus.fireEvent(new LoginInfoUpdatedEvent(DataState.Failed));
			}
			public void onSuccess(LoginInfo result) {
				loginInfo = result;
				eventBus.fireEvent(new LoginInfoUpdatedEvent(result));
			}
		});
	}
	public static LoginInfo getLoginInfo() {
		return loginInfo;
	}
}
